<template>
    <el-form :model="userData" label-width="120px" class="user-login-form">
        <div class="form-content">
            <el-form-item>
                <el-text class="mx-1" size="large">注册账号( •̀ ω •́)</el-text>
            </el-form-item>

            <el-form-item label="邮箱">
                <el-input v-model="userData.user.email" v-on:blur="checkEmailExist" />
            </el-form-item>

            <el-form-item label="密码">
                <el-input v-model="userData.user.password" type="password" />
            </el-form-item>

            <el-row :gutter="20" class="verify-code-row">
                <el-col :span="13">
                    <el-form-item label="验证码">
                        <el-input v-model="userData.code" />
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-image v-if="config.inputEmailUsable" style="width: 80px; height: 45px" :src="config.path"
                        @click="refreshCodeImg" />
                </el-col>
            </el-row>
            <el-form-item label="邮箱验证码" inline="true">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-input v-model="userData.emailCode" type="text" />
                    </el-col>
                    <el-col :span="12">
                        <el-button type="primary" @click="sendEmailCode" :disabled="config.sendEmailCodeDisponible">{{
                            config.sendEmailCodeButtonText }}</el-button>
                    </el-col>
                </el-row>


            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="register" :disabled="config.registerButtonDisponible"
                    style="width: 150px;">注册</el-button>
                <el-button @click="login">登录</el-button>
            </el-form-item>
        </div>
    </el-form>
</template>

<script>


import { useRouter } from 'vue-router'
import { reactive } from 'vue'
import { useStore } from 'vuex';
import _store from "@/store"

import StringUtil from '../../utils/StringUtil.js'
import InfoUtil from '../../utils/InfoUtil.js'
import RequestUtil from '../../utils/RequestUtil.js'



export default {
    props: ['changeShow'],
    setup(props) {
        const store = useStore() || _store;
        const router = useRouter();
        //注册按钮
        const register = () => {
            if (StringUtil.isEmpty(userData.user.email) || StringUtil.isEmpty(userData.user.password)) {
                InfoUtil.warning("账号或密码不能为空")
                return;
            }
            if (StringUtil.isEmpty(userData.emailCode)) {
                InfoUtil.warning("验证码不为空")
                return;
            }
            config.loginButtonDisponible = true;
            RequestUtil.sendPostRequest("/user/register", userData).then(
                (res) => {
                    if (res.code == 200) {
                        InfoUtil.success("注册成功! 即将为您跳转到登录页");
                        localStorage.setItem("userEmail",userData.user.email);
                        setTimeout(()=>{
                            login();
                        },3000);
                        return;
                    } else {
                        InfoUtil.warning(res.message)
                        userData.failNumber = res.data;
                    }
                    //失败后刷新验证码

                    refreshCodeImg();

                    config.loginButtonDisponible = false;
                },
                (error) => {
                    config.loginButtonDisponible = false;
                    InfoUtil.error("请求失败")
                    return;
                }
            );
        }
        //刷新验证码图片
        const refreshCodeImg = () => {
            RequestUtil.sendGetRequestGetImage("/user/createRegisterCode",  {"email":userData.user.email}).then(
                (res) => {
                    if(res!=null){
                        config.path = res;
                    }else{
                        config.path=require("../../assets/img/index/tooManyRequestCodeImg.jpg")
                    }
                },
                (err) => {
                    InfoUtil.error("发送请求失败")
                    return;
                }
            );
        }

        //当邮箱框失去焦点后查询该邮箱是否已经注册
        const checkEmailExist = () => {
        
            //如果用户邮箱已经验证过,则跳过
            if (config.inputEmailUsable) {
                return;
            }
            if (StringUtil.isEmpty(userData.user.email)) {
                InfoUtil.warning("邮箱不能为空")
                return;
            }
            if (!StringUtil.checkEmail(userData.user.email)) {
                InfoUtil.warning("邮箱格式不正确")
                return;
            }
            RequestUtil.sendGetRequest("/user/queryEmailExist", { "email": userData.user.email }).then(
                (res) => {
                    if (res.code != 200) {
                        
                        return;
                    }
                    if (res.data) {
                        InfoUtil.warning(res.message)
                        return;
                    }
                    refreshCodeImg();
                    config.inputEmailUsable = true;
                },
                (err) => {
                    console.log(err);
                    InfoUtil.error("发送请求失败")
                    return;
                }
            );
        }

        //发送邮箱验证码
        const sendEmailCode = () => {
            if (!config.inputEmailUsable || StringUtil.isEmpty(userData.code)) {
                InfoUtil.warning("清先输入图形验证码")
                return;
            }
            if (StringUtil.isEmpty(userData.user.email)) {
                InfoUtil.warning("邮箱不能为空")
                return;
            }
            if (!StringUtil.checkEmail(userData.user.email)) {
                InfoUtil.warning("邮箱格式不正确")
                return;
            }
            const createRegisterEmailCodeRequestData = {
                "email": userData.user.email,
                "code": userData.code
            }
            RequestUtil.sendGetRequest("/user/createRegisterEmailCode", createRegisterEmailCodeRequestData).then(
                (res) => {
                    if (res.code != 200) {
                        refreshCodeImg();
                        userData.code = "";
                        InfoUtil.warning(res.message)
                        return;
                    }
                    InfoUtil.success(res.message)
                    config.sendEmailCodeDisponible = true;
                    //创建定时器来展示发送邮箱按钮上的文字
                    localStorage.setItem("sendRegisterEmailCodeTime", Date.now());
                    let sendEmailCodeInterval = setInterval(() => {
                        let time = Date.now() - localStorage.getItem("sendRegisterEmailCodeTime");
                        //获取秒数
                        time /= 1000;
                        //验证码还在有效期内
                        if (600 > time) {
                            config.sendEmailCodeButtonText = Math.ceil(600 - time) + "秒";
                        } else {
                            config.sendEmailCodeDisponible = false;
                            config.sendEmailCodeButtonText = "发送验证码"
                            shutDownInterval();
                        }

                    }, 1000);
                    config.sendEmailCodeInterval = sendEmailCodeInterval;
                },
                (err) => {
                    InfoUtil.warning("发送请求失败")
                    return;
                }
            );

        }

        //关闭定时器
        const shutDownInterval = () => {
            let interval = config.sendEmailCodeInterval;
            if (interval != null) {
                window.clearInterval(interval);
                config.sendEmailCodeInterval = null;
            }

        }
        //登录按钮
        const login = () => {
            props.changeShow(2);
        }

        const config = reactive({
            //图形验证码路径
            path: "",
            //注册按钮是否禁用
            registerButtonDisponible: false,
            //用户输入完的邮箱是否是可用的
            inputEmailUsable: false,
            //发送验证码按钮是否禁用
            sendEmailCodeDisponible: false,
            //发送验证码按钮上显示的文字
            sendEmailCodeButtonText: "发送验证码",
            //发送验证码按钮禁用定时器
            sendEmailCodeInterval: null
        })

        const userData = reactive({
            user: {
                email: "",
                password: ""
            },
            //图形验证码
            code: "",
            //邮箱验证码
            emailCode: ""

        })
        return {
            userData, config,
            refreshCodeImg, login, register, checkEmailExist, sendEmailCode
        }

    }

}
</script>

<style scoped>
.user-login-form {
    position: absolute;
    height: 40vh;
    width: 30vw;
    background-color: #f2f6fc;
    border-radius: 20px;
    top: calc(50vh - 17.5vh);
    left: 60vw;
}

.el-row {
    align-items: center;
}

.form-content {
    width: 80%;
    height: 80%;
    position: relative;
    top: 2vh;
    left: 10px;
}
</style>